<?php

namespace app\admin\controller;

use app\admin\model\Crontab;
use app\common\controller\Backend;

/**
 * 拍卖品
 *
 * @icon fa fa-circle-o
 */
class Auction extends Backend
{

    /**
     * Auction模型对象
     * @var \app\admin\model\Auction
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Auction;

        $this->model::event('before_insert', function ($row){return $this->beforeSave($row);});
        $this->model::event('before_update', function ($row){return $this->beforeSave($row);});
    }

    protected function beforeSave($row){
        if(in_array($this->request->action(),['add','edit'])){
            if ($row->lng&&$row->lat){
                $res = $this->model->getcity($row->lat,$row->lng);
                if ($res['code']!=1){
                    exception($res['msg']);
                    return false;
                }
                $row->province_id = $res['data']['province_id'];
                $row->city_id = $res['data']['city_id'];
                $row->district_id = $res['data']['district_id'];
            }

        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['auction_id','name','image','images','start_time','end_time','deposit','status','createtime',
                    'is_defer','is_stop','is_pause','is_cancel']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()){
            $params = $this->request->post("row/a", [], 'strip_tags');

            if ($params){
                $start_time = strtotime($params['start_time']);

                $end_time = strtotime($params['end_time']);

                if ($end_time<$start_time){
                    $this->error('结束时间不能小于开始时间');
                }

                if (time() > $end_time) {
                    $this->error('当前时间不能大于结束时间');
                }

                if (time() > $start_time){
                    $params['status'] = 1;
                } else {
                    $params['status'] = 0;
                }
                $params['price'] = $params['initial_price'];
                $result = $this->model->save($params);
                //dump($result);
                //dump($this->model);die;
                if ($result === false) {
                    $this->error($this->model->getError());
                }

                if ($this->model->status == 1){
                    $cron = new Crontab();
                    $cron->setAttr('type','url');
                    $cron->title = '关闭拍卖活动id:'.$this->model->auction_id;
                    $cron->content = request()->domain().'/api/callback/CloseAuction?auction_id='.$this->model->auction_id;
                    $cron->schedule = schedule($end_time);
                    $cron->maximums = 1;
                    $cron->begintime = time();
                    $cron->endtime = $end_time;
                    $cron->status = 'normal';
                    $cron->save();
                } else {
                    $cron = new Crontab();
                    $list = [
                        [
                            'type'=>'url',
                            'title'=>'关闭拍卖活动id:'.$this->model->auction_id,
                            'content'=>request()->domain().'/api/callback/CloseAuction?auction_id='.$this->model->auction_id,
                            'schedule'=>schedule($end_time),
                            'maximums'=>1,
                            'begintime'=>time(),
                            'endtime'=>$end_time,
                            'status'=>'normal'
                        ] ,
                        [
                            'type'=>'url',
                            'title'=>'开启拍卖活动id:'.$this->model->auction_id,
                            'content'=>request()->domain().'/api/callback/OpenAuction?auction_id='.$this->model->auction_id,
                            'schedule'=>schedule($start_time),
                            'maximums'=>1,
                            'begintime'=>time(),
                            'endtime'=>$start_time,
                            'status'=>'normal'
                        ]
                    ];
                    $cron->saveAll($list);
                }
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()){
            $params = $this->request->post("row/a", [], 'strip_tags');

            if ($params){

                $start_time = strtotime($params['start_time']);

                $end_time = strtotime($params['end_time']);

                if ($end_time<$start_time){
                    $this->error('结束时间不能小于开始时间');
                }

                if (time() > $end_time) {
                    $this->error('当前时间不能大于结束时间');
                }

                if (time() > $start_time){
                    $params['status'] = 1;
                } else {
                    $params['status'] = 0;
                }
                $params['price'] = $params['initial_price'];
                $result = $row->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                if (strtotime($params[ 'start_time' ]) <= time()) {
                    $auction = new \app\api\model\Auction();
                    //活动商品启动
                    $auction->cronOpenAuction($ids);
                    Crontab::destroy(['title'=>'关闭拍卖活动id:'.$ids]);
                    Crontab::destroy(['title'=>'开启拍卖活动id:'.$ids]);

                    $cron = new Crontab();
                    $list = [
                        [
                            'type'=>'url',
                            'title'=>'关闭拍卖活动id:'.$ids,
                            'content'=>request()->domain().'/api/callback/CloseAuction?auction_id='.$ids,
                            'schedule'=>schedule($end_time),
                            'maximums'=>1,
                            'begintime'=>time(),
                            'endtime'=>strtotime($end_time),
                            'status'=>'normal'
                        ]
                    ];
                    $cron->saveAll($list);

                } else {
                    Crontab::destroy(['title'=>'关闭拍卖活动id:'.$ids]);
                    Crontab::destroy(['title'=>'开启拍卖活动id:'.$ids]);
                    $cron = new Crontab();
                    $list = [
                        [
                            'type'=>'url',
                            'title'=>'关闭拍卖活动id:'.$ids,
                            'content'=>request()->domain().'/api/callback/CloseAuction?auction_id='.$ids,
                            'schedule'=>schedule($end_time),
                            'maximums'=>1,
                            'begintime'=>time(),
                            'endtime'=>$end_time,
                            'status'=>'normal'
                        ] ,
                        [
                            'type'=>'url',
                            'title'=>'开启拍卖活动id:'.$ids,
                            'content'=>request()->domain().'/api/callback/OpenAuction?auction_id='.$ids,
                            'schedule'=>schedule($start_time),
                            'maximums'=>1,
                            'begintime'=>time(),
                            'endtime'=>$start_time,
                            'status'=>'normal'
                        ]
                    ];
                    $cron->saveAll($list);
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //暂缓
    public function defer($ids= null)
    {
        $detail = $this->model->get($ids);
        $detail->status = 3;
        $detail->is_defer = 1;
        $detail->defer_time = time();
        if ($detail->save()){
            $this->success('成功');
        } else {
            $this->success('失败');
        }
    }

    //暂停
    public function pause($ids= null)
    {
        $detail = $this->model->get($ids);
        $detail->status = 6;
        $detail->is_pause = 1;
        $detail->pause_time = time();
        if ($detail->save()){
            $this->success('成功');
        } else {
            $this->success('失败');
        }
    }

    //中止
    public function stop($ids= null)
    {
        $detail = $this->model->get($ids);
        $detail->status = 4;
        $detail->is_stop = 1;
        $detail->stop_time = time();
        if ($detail->save()){
            $this->success('成功');
        } else {
            $this->success('失败');
        }
    }

    //撤回
    public function cancel($ids= null)
    {
        $detail = $this->model->get($ids);
        $detail->status = 5;
        $detail->is_cancel = 1;
        $detail->cancel_time = time();
        if ($detail->save()){
            $this->success('成功');
        } else {
            $this->success('失败');
        }
    }

}
